package com.snail.service.impl;

import com.snail.model.pojo.BizMediaDoc;
import com.snail.model.vo.UserVo;
import com.snail.service.AiContentService;
import com.snail.manager.AiManager;
import com.snail.service.BizMediaDocService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Slf4j
public class AiContentServiceImpl implements AiContentService {
    /**
     * AI工具类
     */
    @Autowired
    private AiManager aiManager;

    @Resource
    private BizMediaDocService bizMediaDocService;

    @Override
    public String generateAiContentAndSave(String systemPrompt, String userPrompt, Integer videoId, Integer userId, Integer outlineId) {
        // 调用AI生成内容
        String content = aiManager.doSyncUnStableRequest(systemPrompt, userPrompt);

        // 保存至数据库
        BizMediaDoc bizMediaDoc = new BizMediaDoc();
        bizMediaDoc.setContent(content);
        bizMediaDoc.setFileType(1);
        bizMediaDoc.setVideoId(videoId);
        bizMediaDoc.setOutlineId(outlineId);
        bizMediaDoc.setCreateBy(Long.valueOf(userId));

        BizMediaDoc docByUserIdAndVideoId = bizMediaDocService.getDocByUserIdAndOutlineId(new UserVo(userId, videoId, outlineId));
        if (docByUserIdAndVideoId == null) {
            // 新增
            bizMediaDoc.setCreateTime(LocalDateTime.now());
            bizMediaDoc.setUpdateTime(LocalDateTime.now());
            bizMediaDocService.save(bizMediaDoc);
            log.info("AI内容生成成功，已保存到数据库");
        } else {
            // 更新
            bizMediaDoc.setId(docByUserIdAndVideoId.getId());
            bizMediaDoc.setUpdateTime(LocalDateTime.now());
            bizMediaDocService.updateDocById(bizMediaDoc);
            log.info("AI内容生成成功，已更新到数据库");
        }
        return content;
    }
}
